<script setup lang="ts">
import { inject, onMounted, nextTick, watch } from 'vue'
import { type RouteRecordRaw, useRoute, useRouter } from 'vue-router'

interface Props {
  routes: RouteRecordRaw[];
}

defineProps<Props>()
const handleSelect = inject<(path: string) => void>('handleSelect')!;
const router = useRouter()
const route = useRoute()

/**
 * 获取当前路由对应的一级菜单路径
 */
const getActiveMenuPath = () => {
  const matched = route.matched
  if (matched.length >= 2) {
    const secondLevel = matched[1]
    return secondLevel.path
  }
  return route.path
}

/**
 * 处理菜单选择
 */
const hSelect = (key: string) => {
  handleSelect(key)
  // 构建完整路径
  const fullPath = key.startsWith('/') ? key : `/admin/${key}`
  // 获取选中的路由配置
  const selectedRoute = router.getRoutes().find(r => r.path === fullPath)
  // 如果有子路由，跳转到第一个子路由
  if (selectedRoute?.children?.length) {
    const firstChild = selectedRoute.children[0]
    router.push(`${fullPath}/${firstChild.path}`)
  } else {
    router.push(fullPath)
  }
}

/**
 * 初始化菜单状态
 */
const initMenuState = () => {
  const activePath = getActiveMenuPath()
  if (activePath) {
    handleSelect(activePath)
  }
}

// 监听路由变化
watch(() => route.path, initMenuState, { immediate: true })

// 组件挂载时初始化
onMounted(() => {
  nextTick(initMenuState)
})
</script>

<template>
  <el-menu 
    :default-active="getActiveMenuPath()" 
    ellipsis 
    mode="horizontal" 
    :popper-offset="16" 
    @select="hSelect"
  >
    <el-menu-item 
      v-for="route in routes" 
      :key="route.path"
      :index="route.path"
    >
      {{ route.meta?.name }}
    </el-menu-item>
  </el-menu>
</template>

<style scoped lang="scss">

</style>